import { domai, domain } from '../config/index'
import Tips from './tips'
import wepy from 'wepy'
import wait from './delay'

const DEF = [
  {
    validator: res => res.ErrorCode === '000000',
    fail_handing: res => Tips.model('', res.msg || '传输异常，请稍后再试', false)
  }
]

export default class http {
  static Get (url, body= {}, { load = true, loadMsg = '加载中...', header= {}, defFail = true, defEx = true, validator = null, apiType = 0, delay = 500} = {} ) {
    if (!validator) {
     validator = DEF[apiType].validator
    }
    return request('GET', url, body, load, loadMsg, header, defFail, defEx, validator, apiType, delay)
  }
  static Post (url, body= {}, { load = true, loadMsg = '加载中...', header= {}, defFail = true, defEx = true, validator = null, apiType = 0, delay = 500} = {} ) {
    if (!validator) {
      validator = DEF[apiType].validator
    }
    return request('POST', url, body, load, loadMsg, header, defFail, defEx, validator, apiType, delay)
  }
}

async function request (method, url, params = {}, load, loadMsg, header, defFail, defEx, validator, apiType, delay) {
  // AccessToken数据，如不需要请删除
  const authInfo = wepy.$instance.globalData.authInfo
  const handler = {}
  handler.url = !url.startsWith('http') ? domain + url : url
  handler.data = params
  handler.hander = {
    'Accept': 'application/json',
    'Content-type': 'application/json',
    'Authorization': authInfo ? authInfo.AccessToken : '',
    ...header
  }
  handler.method = method
  // 加载框
  if (load) {
    Tips.loading(loadMsg)
  }
  await wait(delay)
  // if (process.env.NODE_ENV === 'development') {
  //   console.warn('url:', handler.url)
  //   console.warn('header:', handler.header)
  //   console.warn('input:', handler.data)
  // }
  return new Promise((resolve, reject) => {
    handler.success = async res => {
      const obj = res.data
      // if (process.env.NODE_ENV === 'development') {
      //   console.warn('output:', obj)
      //   console.warn('')
      // }
      if (res.statusCode === 200) {
        Tips.hideLoading()
        if (validator(obj)) {
          resolve(obj)
        } else {
          if (defFail) {
            // 通用业务失败处理
            await DEF[apiType].fail_handing(obj)
            resolve(null)
          } else {
            resolve(obj)
          }
        }
      } else {
        Tips.hideLoading()
        if (res.statusCode === 401) {
          wepy.$instance.globalData.authInfo = null
          await Toast('您的账号已失效')
          wx.redirectTo({
            url: '/page/login/index'
          })
        } else {
          if (defFail) {
            // 通用业务失败处理
            await DEF[apiType].fail_handing(obj)
            resolve(null)
          } else {
            resolve(obj)
          }
        }
      }
    }
    handler.fail = async err => {
      // if (process.env.NODE_ENV === 'development') {
      //   console.warn('err:', err)
      //   console.warn('')
      // }
      Tips.hideLoading()
      if (defFail) {
        // 通用业务失败处理
        await DEF[apiType].fail_handing(obj)
        resolve(null)
      } else {
        resolve(obj)
      }
    }
    handler.complete = () => load && Tips.hideLoading()
    wx.request(handler)
  })
}
